package com.itlong.cloud.controller.finance;

import com.alibaba.fastjson.JSONArray;
import com.itlong.cloud.POJO.DTO.operate.OperateBusinessChargeDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateProductModelImageDTO;
import com.itlong.cloud.POJO.DTO.operate.OperateProductModelManageGetDTO;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.operate.OperateBusinessOperationLogVO;
import com.itlong.cloud.POJO.VO.operate.OperateProductCodeGetVO;
import com.itlong.cloud.POJO.VO.operate.OperateProductModelManageGetVO;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.AuthAccessRequired;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.enumerate.FileCatalogEnum;
import com.itlong.cloud.enumerate.ecode.BaseErrorCodeEnum;
import com.itlong.cloud.enumerate.ecode.OperateErrorCodeEnum;
import com.itlong.cloud.paymenthub.IOperateProductModelManageServiceClient;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.page.Page;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * <desc>
 *      运营-产品型号管理控制器
 * </desc>
 *
 * @createDate 2020/11/27
 */
@RestController
@RequestMapping("/finance/productModelManage")
@RefreshScope
public class OperateProductModelManageController extends BaseController {
    private static Logger LOG = LoggerFactory.getLogger(OperateProductModelManageController.class);
    @Autowired
    private IOperateProductModelManageServiceClient iOperateProductModelManageServiceClient;
    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;
    /**
     * <desc>
     *      获取业务日志列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author Juguang.S
     * @createDate 2020/11/27
     */
    @ResponseBody
    @PostMapping("getLogPage")
    public Object getLogPage(){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            OperateBusinessChargeDTO operateBusinessChargeDTO= HttpProtocolUtil.parseRequestParamToDTO(OperateBusinessChargeDTO.class,request);
            if (operateBusinessChargeDTO == null || StringUtils.isBlank(operateBusinessChargeDTO.getOuterId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Page<OperateBusinessOperationLogVO> operateBusinessOperationLogVOPage = iOperateProductModelManageServiceClient.getLogPage(operateBusinessChargeDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), operateBusinessOperationLogVOPage);
        } catch (Exception e) {
            throw new DataAccessException("【运营-产品型号管理getLogPage】获取业务日志列表失败",e);
        }
    }


    /**
     * <desc>
     *      分页获取任务书产品型号信息
     * </desc>
     *
     * * @param dto 产品型号信息DTO
     * @return 标准格式化响应结果
     * @author pengwei
     * @createDate 2020/11/30
     */
    @ResponseBody
    @PostMapping(path = "/getPage")
    public Object  getPage(OperateProductModelManageGetDTO dto){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto = HttpProtocolUtil.parseRequestParamToDTO(OperateProductModelManageGetDTO.class,request);
            MessageVO  resVo = iOperateProductModelManageServiceClient.getPage(dto);
            return resVo;
        } catch (Exception e) {
            throw new DataAccessException("【运营-产品型号管理getPage】获取产品型号列表失败",e);
        }
    }

    /**
     * <desc>
     *      获取产品型号信息详情
     * </desc>
     *
     * @param dto 获取产品型号信息DTO
     * @return 标准格式化响应结果
     * @author pengwei
     * @createDate 2020/11/30
     */
    @ResponseBody
    @PostMapping("getOne")
    public Object getOne(OperateProductModelManageGetDTO dto){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateProductModelManageGetDTO.class,request);
            if (dto == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperateProductModelManageGetVO  operateProductModelManageGetVO = iOperateProductModelManageServiceClient.getOne(dto);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), operateProductModelManageGetVO);
        } catch (Exception e) {
            throw new DataAccessException("【运营-产品型号管理getOne】获取产品型号详情失败",e);
        }
    }

    /**
     * <desc>
     *      删除产品型号信息
     * </desc>
     *
     * @param dto 产品型号dto
     * @return 标准格式化响应结果
     * @author pengwei
     * @createDate 2020/12/01
     */
    @AuthAccessRequired
    @LoggerInfo(operateDesc = LogDescConstant.FINANCE_PRODUCT_MODEL_DELETE_LOG_DESC)
    @ResponseBody
    @PostMapping("delete")
    public Object delete(OperateProductModelManageGetDTO dto){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateProductModelManageGetDTO.class,request);
            if (dto == null || StringUtils.isBlank(dto.getModelId())) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String ip = HttpProtocolUtil.getIpAddr(request);
            dto.setIp(ip);
            //返回错误码
            Integer   resultCode  =  iOperateProductModelManageServiceClient.delete(dto);
            if(resultCode==-1){
                return  new MessageVO(OperateErrorCodeEnum.OPERATE_PRODUCT_MODEL_RELATED_RECORDS_EXIST_ERR.getErrorCode());
            }
            return new MessageVO(dto.getModelId(), BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【运营-产品型号管理delete】删除产品型号信息失败",e);
        }
    }


    /**
     * <desc>
     * 添加或者修改产品型号
     * <desc/>
     *
     * @param  dto     参数对象
     * @return Object  标准格式化响应结果
     * @author pengwei
     * @createDate 2020/12/01
     */
    @AuthAccessRequired
    @ResponseBody
    @RequestMapping("/saveOrUpdate")
    @LoggerInfo(operateDesc = LogDescConstant.FINANCE_PRODUCT_MODEL_SAVE_OR_UPDATE_LOG_DESC)
    public Object saveOrUpdate(OperateProductModelManageGetDTO dto) {
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateProductModelManageGetDTO.class,request);
            if (dto == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String ip = HttpProtocolUtil.getIpAddr(request);
            dto.setIp(ip);

            if(StringUtils.isNotBlank(dto.getDeviceImageStr())){
                List<OperateProductModelImageDTO> imageDTOList =  JSONArray.parseArray(dto.getDeviceImageStr(), OperateProductModelImageDTO.class);
                if (!imageDTOList.isEmpty()){
                    String    imgPaths  =  this.uploadImageFiles(dto.getDeviceImageStr());
                    dto.setDeviceImageStr(imgPaths);
                }
            }
            MessageVO resVo = iOperateProductModelManageServiceClient.saveOrUpdate(dto);
            return resVo;
        } catch (Exception e) {
            throw new DataAccessException("【运营-产品型号管理saveOrUpdate】添加或者更新产品型号信息失败",e);
        }
    }



    /**
     * <desc>
     * 上传图片文件处理
     * <desc/>
     *
     * @param  imageStr
     * @return
     * @author pengwei
     * @createDate 2020-12-22
     */
    private String uploadImageFiles(String imageStr) throws Exception {
        List<OperateProductModelImageDTO> productModelImageDTOS = JSONArray.parseArray(imageStr, OperateProductModelImageDTO.class);
        StringBuilder imagePathBuilder = new StringBuilder();
        if (productModelImageDTOS != null) {
            for (OperateProductModelImageDTO dto : productModelImageDTOS) {
                String[] iamgeArray = dto.getImgStr().split(",");
                if (!dto.getImgStr().contains("data:image/")) {
                    this.appendContent(imagePathBuilder, dto.getImgStr());
                    continue;
                }
                String imgPath = uploadImageFile(iamgeArray[1], dto.getImgType(), FileCatalogEnum.OPERATE_PRODUCT_MODEL_IMAGE_FILE);
                this.appendContent(imagePathBuilder, imgPath);
            }
            imagePathBuilder.substring(0, imagePathBuilder.length() - 1);
        }
        return imagePathBuilder.toString();
    }

    /**
     * <desc>
     *      上传图片文件
     * <desc/>
     *
     * @param imageStr 图片二进制
     * @param imageType 图片类型
     * @return
     * @author Chunjian.G
     * @createDate 2017-11-10
     */
    private String uploadImageFile(String imageStr,String imageType, FileCatalogEnum fileCatalog){

        byte[] bytes = null;
        try {
            bytes = new BASE64Decoder().decodeBuffer(imageStr);
        } catch (IOException e) {
            LOG.info("BASE64Decoder().decodeBuffer失败,imageStr不合法", e);
            return null;
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );
        try {
            LOG.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            LOG.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)){
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            }else {
                LOG.info(String.format("图片上传失败，returnCode: %s",returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }


    /**
     * <desc>
     *      分页获取和型号相关联的产品编码列表
     * </desc>
     *
     * @param dto 产品型号信息DTO
     * @return 标准格式化响应结果
     * @author pengwei
     * @createDate 2020/11/30
     */
    @ResponseBody
    @PostMapping(path = "/relatedProcCodeList")
    public Object  relatedProcCodeList(OperateProductModelManageGetDTO   dto){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto= HttpProtocolUtil.parseRequestParamToDTO(OperateProductModelManageGetDTO.class,request);
            Page<OperateProductCodeGetVO> voPage = iOperateProductModelManageServiceClient.getRelatedProcCodePage(dto);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), voPage);
        } catch (Exception e) {
            throw new DataAccessException("【运营-产品型号管理relatedProcCodeList】获取产品型号关联的产品编码列表失败",e);
        }
    }


    /**
     * <desc>
     *      分页获取产品编码列表
     * </desc>
     *
     * @return 标准格式化响应结果
     * @author pengwei
     * @createDate 2020/12/02
     */
    @ResponseBody
    @PostMapping(path = "/proCodeSearch")
    public Object  proCodeSearch(){
        try {
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            OperateProductModelManageGetDTO dto= HttpProtocolUtil.parseRequestParamToDTO(OperateProductModelManageGetDTO.class,request);
            Page<OperateProductCodeGetVO> voPage = iOperateProductModelManageServiceClient.getProcCodePage(dto);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), voPage);
        } catch (Exception e) {
            throw new DataAccessException("【运营-产品型号管理proCodeSearch】获取产品编码列表失败",e);
        }
    }

    /**
     * <desc>
     *      选择性拼接字符串
     * </desc>
     *
     * @Author Zhu.yj
     * @createDate  2020/12/29
     */
    private void appendContent(StringBuilder builder, String content){
        if (builder.length() == 0){
            builder.append(content);
        }else {
            builder.append(",").append(content);
        }
    }
}
